# 百度云智能接口类
import json

import requests

class BaiduAip:

    def __init__(self, client_id='ARRoQoGprqHIjTGsLv34EwKW',
                 client_secret='u3fTyGlvhyPNbfcwP9fIMHBmtTN3CkCR'):
        self.client_id = client_id
        self.client_secret = client_secret

        # 获取token
        self.token = self.get_token(self.client_id, self.client_secret)

    def get_token(self, client_id, client_secret):
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' % (

            client_id, client_secret)

        # print(host)

        response = requests.get(host)

        return response.json()['access_token']

    # 情感倾向分析接口
    def sentiment(self, text,
                  url="https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token="):
        # 增加token
        url += self.token

        # print(url)

        # 指定请求头
        headers = {'Content-Type': 'application/json'}

        # 发起请求
        res = requests.post(url, data=json.dumps({'text': '%s' % text}), headers=headers)

        return res.json()['items'][0]['sentiment']

    # 标签抽取接口
    def comment(self, text, type,
                url="https://aip.baidubce.com/rpc/2.0/nlp/v2/comment_tag?charset=UTF-8&access_token="):
        # 增加token
        url += self.token

        # print(url)

        # 指定请求头
        headers = {'Content-Type': 'application/json'}

        # 发起请求
        res = requests.post(url, data=json.dumps({'text': '%s' % text, 'type': '%s' % int(type)}), headers=headers)

        return res.json()['items']


# bd = BaiduAip()
# print(bd.token)
# print(bd.sentiment('我爱祖国'))
# res = bd.comment('1', 8)
# res = bd.comment('你们家的服务态度不行', 8)
# if res is not None:
#     for i in res:
#         print(i['adj'],)


# 标签表     标签
# 多对多    uid   adj_id    信息    情感
# 用户